package com.learning.netease.optimize.trx.dispatchservice.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

/**
 * ClassName: DispatchConsumer
 * Description: 消息消费
 * Date: 2019/1/30 18:12 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
public class DispatchConsumer {

    @Autowired
    private DispatchService dispatchService;

    @RabbitListener(queues = "orderDispatchQueue")
    public void consumer(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws Exception {
        try {
            JSONObject orderInfo = JSON.parseObject(msg);
            String orderId = orderInfo.getString("orderId");

            // 业务处理。业务这边的操作幂等性（业务orderId主键 或者 订单号单独redis保存）
            dispatchService.dispatch(orderId);

            // 手动确认回执
            channel.basicAck(tag, false);
        } catch (Exception e) {
            // requeue - false 代表不用重发，true 代表需要mq重发
            channel.basicNack(tag, false, false);
        }

    }
}
